package com.hjlsoft.aftp.data.fs;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import com.hjlsoft.aftp.data.DataMeta;
import com.hjlsoft.aftp.data.DataMetaHandle;

public class FsDataMetaHandle implements DataMetaHandle {

	private File basePath;
	
	public FsDataMetaHandle(File basePath) {
		super();
		this.basePath = basePath;
	}

	public DataMeta get(String id) throws IOException{
		File f = getMetaFile(id);
		if (!f.exists()) {
			return null;
		}
		FileInputStream is = new FileInputStream(f);
		DataInputStream dis = new DataInputStream(is);
		@SuppressWarnings("unused")
		int flag = dis.readInt();
		String idInData = dis.readUTF();
		long createTime = dis.readLong();
		long position = dis.readLong();
		long totalSize = dis.readLong();
		int status = dis.readInt();
		dis.close();
		DataMeta dataMeta = new DataMeta();
		dataMeta.setCreateTime(createTime);
		dataMeta.setId(idInData);
		dataMeta.setTotalSize(totalSize);
		dataMeta.setPosition(position);
		dataMeta.setStatus(status);
		return dataMeta;
	}

	public void save(DataMeta dataMeta) throws IOException {
		File f = getMetaFile(dataMeta.getId());
		FileOutputStream os = new FileOutputStream(f);
		DataOutputStream dos = new DataOutputStream(os);
		dos.writeInt(0);
		dos.writeUTF(dataMeta.getId());
		dos.writeLong(dataMeta.getCreateTime());
		dos.writeLong(dataMeta.getPosition());
		dos.writeLong(dataMeta.getTotalSize());
		dos.writeInt(dataMeta.getStatus());
		dos.close();
	}

	public File getMetaFile(String id) {
		return new File(basePath, id + ".meta");
	}
	
}
